<template>
  <div class="app">
    <div class="app__title">Current ID: {{ currentId }}</div>
    <div class="app__peer">
      <input v-model="peerId" />
      <button @click="call">Call</button>
    </div>
    <video ref="video" class="app__video" />
  </div>
</template>

<style>
body {
  margin: 0;
}
</style>

<script>
import { DataConnection } from "peerjs/lib/dataconnection";
import { Peer } from "peerjs/lib/peer";

export default {
  name: "Client",
  data() {
    return {
      peer: null,
      currentId: "",
      peerId: "",
    };
  },
  created() {
    const peer = new Peer({
      host: "192.168.1.101",
      port: 4500,
      path: "/test",
    });
    peer.on("open", (id) => {
      this.currentId = id;
    });
    peer.listAllPeers()
    peer.on("call", (call) => {
      console.log("received call", call);
      call.answer();
      call.on("stream", (mediaStream) => {
        console.log("received stream", mediaStream);
        this.$refs.video.srcObject = mediaStream;
        this.$refs.video.play();
      });
    });
    this.peer = peer;
  },
  destroyed() {
    if (this.peer) {
      this.peer.destroy();
    }
  },
  methods: {
    async call() {
      const mediaStream = await navigator.mediaDevices.getDisplayMedia({
        video: { mediaSource: "screen" },
      });
      this.peer.call(this.peerId, mediaStream);
    },
  },
};
</script>
